package com.yepit.translate.demo;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yepit.translate.util.translate.baidu.BaiduTransApi;
import com.yepit.translate.dto.TransRespose;

import java.util.Map;

/**
 * @author qianlong
 * @description //TODO
 * @Date 2019/4/19 4:33 PM
 **/
public class BaiduDemo {

    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
    private static final String APP_ID = "20190419000289579";
    private static final String SECURITY_KEY = "SnAFHxuaiT5U7xgrG2N1";

    public static void main(String[] args) {
        BaiduTransApi api = new BaiduTransApi(APP_ID, SECURITY_KEY);

        String query = "hello";
        TransRespose result = api.getSingleTransResp(query, "auto", "auto");
        System.out.println(result.getTransResult().getDst());
//        Gson gs = new Gson();
//        TransRespose resp = gs.fromJson(result, new TypeToken<TransRespose>() {
//        }.getType());//把JSON格式
//        Map<String, Object> map = jsonToMap(result);
//        System.out.println(result);
//        System.out.println(unicodeToCn("\\u4f60\\u597d"));
    }

    private static String unicodeToCn(String unicode) {
        /** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格*/
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }

    /**
     * 将json转换成Map对象
     * @param json
     * @return
     */
    public static Map<String, Object> jsonToMap(String json) {
        // TODO Auto-generated method stub
        Gson gson = new Gson();
        Map<String, Object> maps = gson.fromJson(json, new TypeToken<Map<String, Object>>() {
        }.getType());
        return maps;
    }
}
